<template>
	<view class="wrap" :style="{ 'padding-bottom': vuex_keyboardStatus ? '0' : '90rpx' }">
		<view class="title"> 基本信息 </view>
		<u-form class="xh-form" :model="crmFormFields" :rules="crmRules" ref="crmForm" :errorType="['message']">
			<u-form-item label-position="top" :prop="item.data.fieldName" :required="item.data.isNull == 1" v-for="(item, index) in crmForm.crmFields" :key="index" :label="item.data.name">
				<!-- 输入框组件 -->
				<component
					:is="'XhInput'"
					v-if="item.data.formType == 'text' || item.data.formType == 'number' || item.data.formType == 'floatnumber' || item.data.formType == 'mobile' || item.data.formType == 'email'"
					:index="index"
					:item="item"
					:value="item.value"
					:disabled="item.disabled"
					:relation="item.relation"
					:placeholder="'请输入' + item.data.name"
					@value-change="fieldValueChange"
				>
				</component>
				<!-- 单选组件 -->
				<component :is="'XhSelect'" v-if="item.data.formType == 'select'" :index="index" :item="item" :value="item.value" :disabled="item.disabled" :relation="item.relation" @value-change="fieldValueChange"> </component>
				<!-- 时间选择组件 -->
				<component
					:is="'XhDateTime'"
					v-if="item.data.formType == 'datetime' || item.data.formType == 'date'"
					:index="index"
					:item="item"
					:value="item.value"
					:disabled="item.disabled"
					:relation="item.relation"
					@value-change="fieldValueChange"
				>
				</component>
				<!-- 关联表 -->
				<component
					:is="'XhRelativeTable'"
					v-if="item.data.formType == 'contacts' || item.data.formType == 'customer' || item.data.formType == 'contract' || item.data.formType == 'business'"
					:index="index"
					:item="item"
					:value="item.value"
					:disabled="item.disabled"
					:relation="item.relation"
					@value-change="fieldValueChange"
				>
				</component>
				<!-- 新建关联数据 -->
				<component :is="'XhCreate'" v-if="item.data.formType == 'customer_contacts'" :index="index" :item="item" :value="item.value" :disabled="item.disabled" :relation="item.relation" @value-change="fieldValueChange"> </component>
				<!-- 富我文本编辑器 -->
				<component :is="'EditorBar'" v-if="item.data.formType == 'textarea'" :index="index" :item="item" :value="item.value" :disabled="item.disabled" :relation="item.relation" type="bbs" @value-change="fieldValueChange"> </component>
			</u-form-item>
		</u-form>
		<!-- <view>
            <view class="title">
                审批信息
            </view>
        </view> -->
		<view class="xh-buttons">
			<view class="inner">
				<u-button class="xh-button-item" shape="circle" type="warning" @click="saveDraftField" v-if="showDraft">保存草稿</u-button>
				<u-button class="xh-button-item" shape="circle" type="primary" @click="saveField(false, '', 0)">{{ sureBtnTitle }}</u-button>
				<u-button class="xh-button-item" shape="circle" type="warning" @click="saveField(false, '', 1)">匿名发布</u-button>
			</view>
		</view>
	</view>
</template>

<script>
import { filedGetField, filedValidates } from '@/api/customer/common.js';
import { KmsSaveOrUpdateBbs } from '@/api/kms/bbs.js';
import XhInput from '@/pages/customerManagement/common/components/CreateCom/XhInput';
import XhSelect from '@/pages/customerManagement/common/components/CreateCom/XhSelect';
import XhDateTime from '@/pages/customerManagement/common/components/CreateCom/XhDateTime';
import XhRelativeTable from '@/pages/customerManagement/common/components/CreateCom/XhRelativeTable';
import XhTextarea from '@/pages/customerManagement/common/components/CreateCom/XhTextarea';
import XhCreate from '@/pages/customerManagement/common/components/CreateCom/XhCreate.vue';
import EditorBar from '@/pages/kmsManagement/common/editor.vue';
import kmsTypeModel from '@/pages/kmsManagement/kmsFunList/model/kmsTypeModel.js';
import { crmContactsSave } from '@/api/customer/contacts.js';
import { crmCustomerSave } from '@/api/customer/customer.js';
import { crmLeadsSave } from '@/api/customer/leads.js';

/* 	import { quillEditor } from "vue-quill-editor"; */
export default {
	data() {
		return {
			params: null,
			crmForm: {
				crmFields: [],
			},
			crmFormFields: {},
			crmRules: {},
			crmType: '',
			isUpdate: false,
			crmData: {},
		};
	},
	components: {
		XhInput,
		XhSelect,
		XhDateTime,
		XhRelativeTable,
		XhTextarea,
		XhCreate,
		EditorBar,
		/* 	quillEditor */
	},
	onLoad(option) {
		//调试结束后启用该代码
		this.params = option.params ? JSON.parse(decodeURIComponent(option.params)) : {};
		this.crmType = this.params.crmType;
		uni.setNavigationBarTitle({
			title: this.handleBarTitle(this.params.crmType),
		});
		this.getFields();
	},

	onShow() {
		console.log(' --->>> ')
		if (uni.getStorageSync('refreshData')) {
			this.getFields();
		}
		console.log(this.vuex_keyboardStatus, 777);
	},

	computed: {
		// 草稿按钮
		showDraft() {
			if (this.crmType === 'contract' || this.crmType === 'receivables' || this.crmType === 'leads' || this.crmType === 'customer' || this.crmType === 'business' || this.crmType === 'preSales') {
				return true;
			}
			return false;
		},
		sureBtnTitle() {
			if (this.crmType === 'contract' || this.crmType === 'receivables' || this.crmType === 'leads' || this.crmType === 'customer' || this.crmType === 'business' || this.crmType === 'preSales') {
				return '提交审核';
			} else if (this.crmType === 'bbs') {
				return '发布';
			}
			return '保存';
		},
	},

	methods: {
		handleBarTitle(type) {
			if (type == 'leads') {
				return '新建潜在客户';
			}
			if (type == 'customer') {
				return '新建目标客户';
			}
			if (type == 'contacts') {
				return '新建联系人';
			}
		},

		// 更改值
		fieldValueChange(data) {
			let item = this.crmForm.crmFields[data.index];
			item.value = data.value;
			//用于校验
			if (data.value && data.value.length) {
				if (item.data.isUnique == 1 || item.data.fieldType == 1) {
					this.crmFormFields[data.fieldName] = data.value;
				} else {
					this.crmFormFields[data.fieldName] = 'TRUE';
				}
			} else {
				this.crmFormFields[data.fieldName] = '';
			}
		},

		// 获取
		getFields() {
			let self = this;
			let params = {
				label: kmsTypeModel[this.crmType],
			};
			if (this.params.id) {
				this.isUpdate = true;
				this.crmData = this.params.data;
				console.log(' --->>> ')
				console.log(this.crmData)
				params.id = this.params.id;
			}
			filedGetField(params).then((res) => {
				self.getCrmRulesAndModel(res.data);
			});
		},

		getCrmRulesAndModel(list) {
			let self = this;
			let fields = [];
			let formFields = {};
			let crmRules = {};
			for (let index = 0; index < list.length; index++) {
				const item = list[index];

				/**
				 * 规则数据
				 */

				crmRules[item.fieldName] = this.getItemRulesArrayFromItem(item);
				/**
				 * 表单数据
				 */
				let params = {};
				params['key'] = item.fieldName;
				params['data'] = item;
				params['disabled'] = item.isDisabled == 1;
				params['value'] = item.value;
				params['relation'] = {}; // 自定义参数
				//将表单中涉及的字段放到crmFormFields，用户后续form的校验
				formFields[item.fieldName] = item.value ? item.value : '';

				if (item.formType == 'datetime') {
					// params['relation']['dateType'] = 'datetime-all';
				} else if (item.formType == 'customer') {
					//关联数据类型actionType
					if (item.value.length) {
						params['value'] = item.value;
					} else {
						params['value'] = [];
					}
					params['relation']['actionType'] = 'customer';
				} else if (item.formType == 'customer_contacts') {
					//关联数据类型actionType
					if (item.value.customerContacts && item.value.customerContacts.length) {
						params['value'] = item.value.customerContacts ? item.value.customerContacts : [];
					} else {
						params['value'] = [];
					}
					// actionType 指当前字段所定类型
					// relativeType 指是关联类型，即用到该字段的业务类型
					params['relation']['relativeType'] = 'customer';
					params['relation']['actionType'] = 'contacts';
				} else {
				}
				// 暂时过滤掉定位
				if (item.formType == 'map_address') {
					params['key'] = 'detailAddress';
					params['data'] = {
						name: '详细地址',
						formType: 'text',
					};
					params['value'] = item.value && item.value.detailAddress ? item.value.detailAddress : '';
				}
				fields.push(params);
			}
			
			this.crmForm.crmFields = fields;
			this.crmFormFields = formFields;
			console.log(this.crmForm)
			this.crmRules = crmRules;
			self.$nextTick(function () {
				self.$refs.crmForm.setRules(self.crmRules);
			});
		},

		getItemRulesArrayFromItem(item) {
			var tempList = [];
			// 验证必填
			if (item.isNull == 1) {
				if (item.formType == 'customer_contacts') {
					var validateFun = (rule, value, callback) => {
						if (value.length) {
							callback();
						} else {
							callback(new Error(item.name + '不能为空'));
						}
					};
					tempList.push({
						required: true,
						validator: validateFun,
						trigger: '',
					});
				} else {
					tempList.push({
						required: true,
						message: item.name + '不能为空',
						trigger: ['blur', 'change'],
					});
				}
			}

			// 验证唯一
			if (item.isUnique == 1) {
				var validateUnique = (rule, value, callback) => {
					if (value.length == 0 || !value) {
						callback();
					} else {
						var validatesParams = {};
						validatesParams.fieldId = item.fieldId;
						// if (isArray(value)) {
						//     let postValue = ''
						//     if (value.length > 0) {
						//         if (
						//             rule.item.formType == 'user' ||
						//             rule.item.formType == 'structure'
						//         ) {
						//             postValue = value
						//                 .map(valueItem => {
						//                     return rule.item.formType == 'user' ?
						//                         valueItem.userId :
						//                         valueItem.id
						//                 })
						//                 .join(',')
						//         } else if (rule.item.fieldName == 'categoryId') {
						//             if (value && value.length) {
						//                 postValue = value[value.length - 1]
						//             } else {
						//                 postValue = ''
						//             }
						//         } else if (rule.item.formType == 'checkbox') {
						//             postValue = value.join(',')
						//         }
						//     }
						//     validatesParams.value = postValue
						// } else {
						//     validatesParams.value = value
						// }
						if (this.isUpdate) {
							validatesParams.batchId = this.crmData.batchId;
						}
						validatesParams.value = value;
						filedValidates(validatesParams)
							.then((res) => {
								callback();
							})
							.catch((error) => {
								callback(new Error(error.msg ? error.msg : '验证出错'));
							});
					}
				};
				tempList.push({
					validator: validateUnique,
					trigger: item.formType == 'checkbox' || item.formType == 'select' ? ['change'] : ['blur', 'change'],
				});
			}

			// if (item.formType == 'number') {
			//     var validateCRMNumber = (rule, value, callback) => {
			//         if (!value || value == '' || regexIsCRMNumber(value)) {
			//             callback()
			//         } else {
			//             callback(new Error('数字的整数部分须少于12位，小数部分须少于4位'))
			//         }
			//     }
			//     tempList.push({
			//         validator: validateCRMNumber,
			//         item: item,
			//         trigger: ['blur']
			//     })
			// } else if (item.formType == 'floatnumber') {
			//     var validateCRMMoneyNumber = (rule, value, callback) => {
			//         if (!value || value == '' || regexIsCRMMoneyNumber(value)) {
			//             callback()
			//         } else {
			//             callback(new Error('货币的整数部分须少于10位，小数部分须少于2位'))
			//         }
			//     }
			//     tempList.push({
			//         validator: validateCRMMoneyNumber,
			//         item: item,
			//         trigger: ['blur']
			//     })
			// } else
			if (item.formType == 'mobile') {
				var validateCRMMobile = (rule, value, callback) => {
					if (!value || value == '' || this.$u.test.mobile(value)) {
						callback();
					} else {
						callback(new Error('手机格式有误'));
					}
				};
				tempList.push({
					validator: validateCRMMobile,
					trigger: ['blur'],
				});
			} else if (item.formType == 'email') {
				var validateCRMEmail = (rule, value, callback) => {
					if (!value || value == '' || this.$u.test.email(value)) {
						callback();
					} else {
						callback(new Error('邮箱格式有误'));
					}
				};
				tempList.push({
					validator: validateCRMEmail,
					trigger: ['blur'],
				});
			}
			return tempList;
		},

		//数据保存
		saveData() {
			let test = this.$refs.crmForm.validate();
		},

		// ==================== 保存数据 ===================
		// 保存草稿
		saveDraftField() {
			this.saveField(false, true);
		},
		// 保存数据
		saveField(saveAndCreate, isDraft = false, num) {
			// this.saveAndCreate = saveAndCreate
			this.$refs.crmForm.validate((valid) => {
				if (valid) {
					// if (this.showExamine) {
					//     /** 验证审批数据 */
					//     if (isDraft) {
					//         // 不验证数据
					//         var params = this.getSubmiteParams(this.crmForm.crmFields)
					//         if (
					//             this.examineInfo.examineType === 2 &&
					//             this.examineInfo.hasOwnProperty('value') &&
					//             this.examineInfo.value.length
					//         ) {
					//             params['checkUserId'] = this.examineInfo.value[0].userId
					//         }
					//         params.entity.checkStatus = 5
					//         this.submiteParams(params)
					//     } else {
					//         this.$refs.examineInfo.validateField(() => {
					//             var params = this.getSubmiteParams(this.crmForm.crmFields)
					//             if (this.examineInfo.examineType === 2) {
					//                 params['checkUserId'] = this.examineInfo.value[0].userId
					//             }
					//             if ((this.crmType === 'leads' || this.crmType === 'customer') && (
					//                     params.entity.customer_contacts == undefined || params.entity
					//                     .customer_contacts.length === 0)) {
					//                 this.$message.error('请添加联系人')
					//                 return
					//             }
					//             this.submiteParams(params)
					//         })
					//     }
					// } else {

					// }
					var params = this.getSubmiteParams(this.crmForm.crmFields, num);
					if (this.isUpdate) {
						params.entity[this.crmType + 'Id'] = this.params.id;
						params.entity.batchId = this.crmData.batchId;
					}
					if (isDraft) {
						params.entity.checkStatus = 5;
					} else {
						if ((this.crmType === 'leads' || this.crmType === 'customer') && !params.entity.customer_contacts.length) {
							this.$u.toast('请添加联系人');
							return;
						}
					}
					this.submiteParams(params);
				} else {
					this.$u.toast('存在字段填写不规范！');
					return false;
				}
			});
		},
		/** 拼接上传传输 */
		getSubmiteParams(array, num) {
			var params = {
				entity: {},
				field: [],
			};
			for (let index = 0; index < array.length; index++) {
				const element = array[index];
				if (element.key == 'product') {
					this.getProductParams(params, element);
				} else if (element.key == 'map_address') {
					this.getCustomerAddressParams(params.entity, element);
				} else if (element.key == 'customer_contacts') {
					params.entity[element.key] = element.value;
				} else if (element.data.fieldType == 1) {
					params.entity['isAnonymous'] = num;
					params.entity[element.key] = this.getRealParams(element) || '';
				} else {
					element.data.value = this.getRealParams(element);
					params.field.push(element.data);
				}
			}

			if (this.businessInfo != null) {
				params.businessInfo = this.businessInfo;
			}
			return params;
		},

		// 关联客户 联系人等数据要特殊处理
		getRealParams(element) {
			if (element.key == 'customer_id' || element.key == 'contacts_id' || element.key == 'business_id' || element.key == 'leads_id' || element.key == 'contract_id') {
				if (element.value && element.value.length) {
					const key = element.key.replace('_id', 'Id');
					return element.value[0][key];
				} else {
					return '';
				}
			} else if (element.data.formType == 'user' || element.data.formType == 'structure') {
				return element.value
					.map(function (item, index, array) {
						return element.data.formType == 'user' ? item.userId : item.id;
					})
					.join(',');
			} else if (element.data.formType == 'file') {
				if (element.value && element.value.length > 0) {
					return element.value[0].batchId;
				}
				return '';
			} else if (element.key == 'category_id') {
				if (element.value && element.value.length > 0) {
					return element.value[element.value.length - 1];
				}
				return '';
			} else if (element.data.formType == 'checkbox') {
				if (element.value && element.value.length > 0) {
					return element.value.join(',');
				}
				return '';
			}
			return element.value;
		},

		/** 上传 */
		submiteParams(params) {
			var crmRequest = this.getSubmiteRequest();
			// if (this.action.type == 'update') {
			//     const key = this.crmType == 'receivables_plan' ? 'plan' : this.crmType
			//     if (this.crmType == 'leads') {
			//         params.entity['customerId'] = this.action.id
			//     } else {
			//         params.entity[key + 'Id'] = this.action.id
			//     }
			//     params.entity.batchId = this.action.batchId
			// }

			// 相关添加时候的多余提交信息
			// if (
			//     this.action.relativeData &&
			//     Object.keys(this.action.relativeData).length
			// ) {
			//     params = { ...params,
			//         ...this.action.relativeData
			//     }
			// }
			crmRequest(params)
				.then((res) => {
					// this.loading = false
					// if (this.crmType == 'customer') {
					//     if (!this.saveAndCreate) {
					//         this.$message.success(
					//             this.action.type == 'update' ? '编辑成功' : '添加成功'
					//         )
					//         this.hidenView()
					//     }
					// } else {
					//     this.hidenView()
					//     this.$message.success(
					//         this.action.type == 'update' ? '编辑成功' : '添加成功'
					//     )
					// }
					// 回到保存成功
					// this.$emit('save-success', {
					//     type: this.crmType,
					//     data: res.data || {},
					//     saveAndCreate: this.saveAndCreate
					// })
					// uni.navigateTo({
					// 	url: '/pages/kmsManagement/kmsFunList/bbs/bbsIndex',
					// });
					uni.navigateBack();
					uni.setStorageSync('refreshData', true);
				})
				.catch(() => {
					this.loading = false;
				});
		},
		/** 获取上传url */
		getSubmiteRequest() {
			if (this.crmType == 'bbs') {
				return KmsSaveOrUpdateBbs;
			}
		},

		getProductParams(params, element) {
			if (element.value) {
				params['product'] = element.value.product ? element.value.product : [];
				params.entity['totalPrice'] = element.value.totalPrice ? element.value.totalPrice : 0;
				params.entity['discountRate'] = element.value.discountRate ? element.value.discountRate : 0;
			} else {
				params['product'] = [];
				params.entity['totalPrice'] = '';
				params.entity['discountRate'] = '';
			}
		},
		// 获取客户位置参数
		getCustomerAddressParams(params, element) {
			params['address'] = element.value.address ? element.value.address.join(',') : '';
			params['detailAddress'] = element.value.detailAddress;
			params['location'] = element.value.location;
			params['lng'] = element.value.lng;
			params['lat'] = element.value.lat;
		},
	},
};
</script>

<style scoped lang="scss">
/* @import 'quill/dist/quill.core.css';
	@import 'quill/dist/quill.snow.css';
	@import 'quill/dist/quill.bubble.css'; */
.wrap {
	// padding-bottom: 90rpx;
}

.title {
	width: 100%;
	padding: 20px 15px 10px;
	box-sizing: border-box;
}

.xh-form {
	padding: 0 30rpx;
}

.xh-buttons {
	height: 70px;
	width: 100%;

	.inner {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		z-index: 10;
		text-align: center;
		display: flex;
		justify-content: center;
		padding: 15px;
	}

	.xh-button-item {
		border: none;
		margin: 0 10px;
	}
}

.u-form {
	background: #fff;
}

.u-form-item /deep/ {
	padding: 20rpx 0 0 0;
	line-height: 1;

	.u-form-item__message {
		margin: 0;
		padding-bottom: 10rpx;
	}

	.u-form-item--left {
		margin: 0 !important;
	}

	.u-form-item--left__content__label {
		margin-bottom: 10px;
	}
}
</style>
